package com.app.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Base64;


public class Utils_Image {

	
	
	/**
	 * 显示网络图片
	 * 
	 * @param url
	 * @return
	 */
	private Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
			conn.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/*
	public static Bitmap returnBitMap(String url, BitmapFactory.Options options) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is, null, options);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	*/
	
	 
	
	/**
	 * 加载网络图片
	 * @author matengfei
	 * @param url
	 * @return
	 */
	public String UrlPicSaveToDisk(String url) {

		String newImgPath = "";
		FileOutputStream fos;

		Bitmap bitmap = returnBitMap(url);    

		try {
			if (null != bitmap) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				Date dt = new Date();
				// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
				String picName = sdf.format(dt);
				// String picName = file.getName();
				newImgPath += File.separator + picName + ".jpg";
				fos = new FileOutputStream(newImgPath);
				int quality = 100;
				bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
				fos.flush();
				fos.close();
			} else {
				return null;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			if (!bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}

		return newImgPath;
	}

	/**
	 * 为避免大图在上传和下载后显示，导致内存溢出，特对大图上传，采用压缩后在上传； 采用如下的图片压缩方案： 阈值： 尺寸: 长边1024;
	 * 体积：200KB
	 * 
	 * @param path
	 * 根据大图片，生成能够处理的小图片文件；
	 * @return
	 */
	private static String imageCompress(String imgPath) {
		if (null == imgPath || "".equals(imgPath)) {
			return "";
		}

		File file = new File(imgPath);
		String imgFileName = file.getName();
		String newImgPath = imgPath.substring(0, imgPath.indexOf(imgFileName));
		FileOutputStream fos = null;
		Bitmap bitmap = null;

		if (file.exists() && file.length() / 1024 > 200) {
			// 1 获取图片的原始大小
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, options);
			if (options.mCancel || options.outWidth == -1
					|| options.outHeight == -1) {
				return "";
			}
			int originWidth = options.outWidth;
			int originHeight = options.outHeight;

			int size_x = 640; // ..

			// 2. 按同比例压缩计算目标尺寸
			int dstWidth = originWidth;
			int dstHeight = originHeight;
			Utils_Log.i("TAG", "原始尺寸：" + dstWidth + "," + dstHeight);
			System.out.println("原始尺寸：" + dstWidth + "," + dstHeight);
			if (originWidth > size_x) {
				dstWidth = size_x;
				dstHeight = (int) ((float) size_x * originHeight / originWidth);

			}

			System.out.println("压缩尺寸：" + dstWidth + "," + dstHeight);
			// 3. 按照目标尺寸对图片进行解码，创建Bitmap
			options.inSampleSize = computeSampleSize(options, dstWidth,
					dstHeight);
			Utils_Log.i("TAG", "computeSampleSize(options, dstWidth,dstHeight)="
					+ computeSampleSize(options, dstWidth, dstHeight));
			System.out
					.println("computeSampleSize(options, dstWidth,dstHeight)="
							+ computeSampleSize(options, dstWidth, dstHeight));
			options.inJustDecodeBounds = false;
			options.inDither = false;
			Utils_Log.i("TAG", "inSampleSize：" + options.inSampleSize);
			Bitmap sourceBitmap = BitmapFactory.decodeFile(imgPath, options);
			options = null;
			if (null == sourceBitmap) {
				return null;
			}
			// 3.2 按照同比例缩放创建Bitmap
			bitmap = Bitmap.createScaledBitmap(sourceBitmap, dstWidth,
					dstHeight, false);

			// 4. 对Bitmap进行压缩处理，生成JPEG格式的图片
			try {
				if (null != bitmap) {
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					Date dt = new Date();
					// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
					String picName = sdf.format(dt);
					// String picName = file.getName();
					newImgPath += File.separator + picName + ".jpg";
					fos = new FileOutputStream(newImgPath);
					int quality = 100;
					bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
					fos.flush();
					fos.close();
				} else {
					return null;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// stony
				if (!sourceBitmap.isRecycled()) {
					sourceBitmap.recycle();
				}
				if (!bitmap.isRecycled()) {
					bitmap.recycle();
				}
			}
		} else {
			newImgPath = imgPath;
		}
		return newImgPath;
	}

	
	/**
	 * 计算缩放比
	 * 
	 * @param options
	 * @param target
	 * @return
	 */
	private static int computeSampleSize(BitmapFactory.Options options,
			int targetWidth, int targetHeight) {
		int w = options.outWidth;
		int h = options.outHeight;

		int candidateW = w / targetWidth;
		int candidateH = h / targetHeight;
		int candidate = Math.max(candidateW, candidateH);

		if (candidate == 0)
			return 1;
		return candidate;
	}

	/**
	 * 根据图片路径将图片Base64转换为字符串
	 * 
	 * @param path
	 * @return
	 */
	@SuppressLint("NewApi")
	private static String bitmaptoString(String path) {
		// 将Bitmap转换成字符串
		String string = null;
		Bitmap bitmap = decodeFile(path);
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		bitmap.recycle();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		try {
			bStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return string;
	}
	
	

	/**
	 * y
	 * 
	 * @param f
	 * @return
	 */
	public static Bitmap decodeFile(String f) {
		try {
			// decode image size
			File file = new File(f);
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(file), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 320;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 <= REQUIRED_SIZE
						|| height_tmp / 2 <= REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			o2.inPreferredConfig = Bitmap.Config.RGB_565;
			o2.inPurgeable = true;
			o2.inInputShareable = true;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	/**
	 * 将图片转化为字符串，
	 * 如果文件超出大小，创建较小文件再转换成base64流
	 */
	public static String oom(String path) {
		return bitmaptoString(imageCompress(path));
	}
	
	/**
	 * 将图片转化为base64流，
	 * 
	 */
	public static String oom_2(String imgPath) {
		
		if (null == imgPath || "".equals(imgPath)) {
			return "";
		}

		File file = new File(imgPath);
		String imgFileName = file.getName();
		String newImgPath = imgPath.substring(0, imgPath.indexOf(imgFileName));
		FileOutputStream fos = null;
		Bitmap bitmap = null;

		if (file.exists() && file.length() / 1024 > 200) {
			// 1 获取图片的原始大小
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, options);
			if (options.mCancel || options.outWidth == -1
					|| options.outHeight == -1) {
				return "";
			}
			int originWidth = options.outWidth;
			int originHeight = options.outHeight;

			int size_x = 640; // ..

			// 2. 按同比例压缩计算目标尺寸
			int dstWidth = originWidth;
			int dstHeight = originHeight;
			Utils_Log.i("TAG", "原始尺寸：" + dstWidth + "," + dstHeight);
			System.out.println("原始尺寸：" + dstWidth + "," + dstHeight);
			if (originWidth > size_x) {
				dstWidth = size_x;
				dstHeight = (int) ((float) size_x * originHeight / originWidth);

			}

			System.out.println("压缩尺寸：" + dstWidth + "," + dstHeight);
			// 3. 按照目标尺寸对图片进行解码，创建Bitmap
			options.inSampleSize = computeSampleSize(options, dstWidth,
					dstHeight);
			Utils_Log.i("TAG", "computeSampleSize(options, dstWidth,dstHeight)="
					+ computeSampleSize(options, dstWidth, dstHeight));
			System.out
					.println("computeSampleSize(options, dstWidth,dstHeight)="
							+ computeSampleSize(options, dstWidth, dstHeight));
			options.inJustDecodeBounds = false;
			options.inDither = false;
			Utils_Log.i("TAG", "inSampleSize：" + options.inSampleSize);
			Bitmap sourceBitmap = BitmapFactory.decodeFile(imgPath, options);
			options = null;
			if (null == sourceBitmap) {
				return null;
			}
			// 3.2 按照同比例缩放创建Bitmap
			bitmap = Bitmap.createScaledBitmap(sourceBitmap, dstWidth,
					dstHeight, false);

			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, bStream);
			byte[] bytes = bStream.toByteArray();
			bitmap.recycle();
			String string = Base64.encodeToString(bytes, Base64.DEFAULT);
			try {
				bStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return string;
				
		} else {
			//newImgPath = imgPath;
			// 将Bitmap转换成字符串
			String string = null;
			bitmap = decodeFile(imgPath);
			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, bStream);
			byte[] bytes = bStream.toByteArray();
			bitmap.recycle();
			string = Base64.encodeToString(bytes, Base64.DEFAULT);
			try {
				bStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return string;
			
		}
		
		
	
		
		
	}
	

	/*
	 * 返回图片的数据流
	 */
	public static String decodeBitmap(String imgPath, boolean bUseRaw)
	{
		
		if (null == imgPath || "".equals(imgPath)) {
			return "";
		}

		File file = new File(imgPath);
		String imgFileName = file.getName();
		String newImgPath = imgPath.substring(0, imgPath.indexOf(imgFileName));
		FileOutputStream fos = null;
		Bitmap bitmap = null;

		if (file.exists() && file.length() / 1024 > 200 && bUseRaw == false) {
			// 1 获取图片的原始大小
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, options);
			if (options.mCancel || options.outWidth == -1
					|| options.outHeight == -1) {
				return "";
			}
			int originWidth = options.outWidth;
			int originHeight = options.outHeight;

			int size_x = 640; // ..

			// 2. 按同比例压缩计算目标尺寸
			int dstWidth = originWidth;
			int dstHeight = originHeight;
			Utils_Log.i("TAG", "原始尺寸：" + dstWidth + "," + dstHeight);
			System.out.println("原始尺寸：" + dstWidth + "," + dstHeight);
			if (originWidth > size_x) {
				dstWidth = size_x;
				dstHeight = (int) ((float) size_x * originHeight / originWidth);

			}

			System.out.println("压缩尺寸：" + dstWidth + "," + dstHeight);
			// 3. 按照目标尺寸对图片进行解码，创建Bitmap
			options.inSampleSize = computeSampleSize(options, dstWidth,
					dstHeight);
			Utils_Log.i("TAG", "computeSampleSize(options, dstWidth,dstHeight)="
					+ computeSampleSize(options, dstWidth, dstHeight));
			System.out
					.println("computeSampleSize(options, dstWidth,dstHeight)="
							+ computeSampleSize(options, dstWidth, dstHeight));
			options.inJustDecodeBounds = false;
			options.inDither = false;
			Utils_Log.i("TAG", "inSampleSize：" + options.inSampleSize);
			Bitmap sourceBitmap = BitmapFactory.decodeFile(imgPath, options);
			options = null;
			if (null == sourceBitmap) {
				return null;
			}
			// 3.2 按照同比例缩放创建Bitmap
			bitmap = Bitmap.createScaledBitmap(sourceBitmap, dstWidth,
					dstHeight, false);

			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, bStream);
			String string = bStream.toString();
			bitmap.recycle();
			try {
				bStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return string;
				
		} else {
			// 将Bitmap转换成字符串
			String string = "";
			bitmap = decodeFile(imgPath);
			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, bStream);
			string = bStream.toString();
			bitmap.recycle();
			try {
				bStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return string;
			
		}
		
		
	}
	
	
	 
 

};
